package alipay.openplatform.edu.campus.jiuye.service.services.topic;

import alipay.openplatform.edu.campus.jiuye.common.utils.CopyVoPo;
import alipay.openplatform.edu.campus.jiuye.common.utils.ObjectUtils;
import alipay.openplatform.edu.campus.jiuye.dao.mappers.topic.TopicCityInfoMapper;
import alipay.openplatform.edu.campus.jiuye.model.po.TopicCityInfoPO;
import alipay.openplatform.edu.campus.jiuye.model.vo.CityVO;
import alipay.openplatform.edu.campus.jiuye.service.iservice.topic.ITopicCityInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题-城市表的相关操作
 */
@Service
public class TopicCityInfoService implements ITopicCityInfoService {

    @Autowired
    private TopicCityInfoMapper topicCityInfoMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addCities(int topicId,List<CityVO> cityVOs) {
        List<TopicCityInfoPO> cityInfoPOs = changeVOToPO(topicId, cityVOs);
        topicCityInfoMapper.insert(cityInfoPOs);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateCities(Integer topicId, List<CityVO> cityVOs) {
        //清空数据
        topicCityInfoMapper.deleteByTopicId(topicId);
        List<TopicCityInfoPO> cityInfoPOs = changeVOToPO(topicId, cityVOs);
        topicCityInfoMapper.insert(cityInfoPOs);
    }

    @Override
    public List<CityVO> getCitiesByTopicId(Integer topicId) {
        List<TopicCityInfoPO> cityInfoPOs = topicCityInfoMapper.selectByTopicId(topicId);
        List<CityVO> cityVOs = new ArrayList<CityVO>();
        for (TopicCityInfoPO cityInfoPO : cityInfoPOs) {
            CityVO cityVO = new CityVO();
            cityVO.setCityId(cityInfoPO.getCityId());
            cityVO.setCityName(cityInfoPO.getAreaName());
            cityVOs.add(cityVO);
        }
        return cityVOs;
    }

    @Override
    public void deleteCityByTopicId(Integer topicId) {
        topicCityInfoMapper.deleteByTopicId(topicId);
    }


    private List<TopicCityInfoPO> changeVOToPO(int topicId,List<CityVO> cityVOs){
        List<TopicCityInfoPO> cityInfoPOs = new ArrayList<TopicCityInfoPO>();
        for (CityVO cityVO : cityVOs) {
            if (ObjectUtils.isNull(cityVO)){
                continue;
            }
            TopicCityInfoPO cityInfoPO = new TopicCityInfoPO();
            cityInfoPO.setTopicId(topicId);
            cityInfoPO.setCityId(cityVO.getCityId());
            cityInfoPO.setAreaName(cityVO.getCityName());
            cityInfoPOs.add(cityInfoPO);
        }
        return cityInfoPOs;
    }
}